package com.qk.management.task;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.qk.common.config.AliYunOSSProperties;
import com.qk.common.util.AliyunOSSOperators;
import com.qk.management.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class OssGarbageCleanupTask {

    @Autowired
    private AliyunOSSOperators ossOperators;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AliYunOSSProperties aliYunOSSProperties; // 明确注入

    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanOssFiles() {
        try {
            // 获取数据库中所有有效的文件URL
            List<String> validUrls = userMapper.selectValidFileUrls();

            // 获取OSS桶中的所有文件列表
            List<String> ossFileList = ossOperators.listAllFiles();

            // 找出需要删除的文件（不在数据库中的文件）
            // 修改后的文件对比逻辑
            List<String> filesToDelete = new ArrayList<>();
            for (String ossFile : ossFileList) {
                boolean isValid = false;
                for (String validUrl : validUrls) {
                    // 提取URL中的文件路径部分进行比较
                    String fileKey = extractFileKeyFromUrl(validUrl);
                    if (ossFile.equals(fileKey)) {
                        isValid = true;
                        break;
                    }
                }
                if (!isValid) {
                    filesToDelete.add(ossFile);
                }
            }

            // 删除冗余文件
            if (!filesToDelete.isEmpty()) {
                deleteFiles(filesToDelete);
                System.out.println("成功删除" + filesToDelete.size() + "个冗余文件");
            }

        } catch (Exception e) {
            System.err.println("清理OSS文件时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }



    private void deleteFiles(List<String> fileKeys) throws Exception {
        OSS ossClient = null;
        try {
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

            ossClient = OSSClientBuilder.create()
                    .endpoint(aliYunOSSProperties.getEndpoint())
                    .credentialsProvider(new EnvironmentVariableCredentialsProvider())
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(aliYunOSSProperties.getRegion())
                    .build();

            ossClient.deleteObjects(new DeleteObjectsRequest(aliYunOSSProperties.getBucketName()).withKeys(fileKeys));
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    // 提取文件key的方法
    private String extractFileKeyFromUrl(String url) {
        try {
            // 假设URL格式为 https://bucket.oss-region.aliyuncs.com/path/to/file.jpg
            int index = url.indexOf(aliYunOSSProperties.getBucketName() + ".");
            if (index != -1) {
                index = url.indexOf("/", index);
                if (index != -1) {
                    return url.substring(index + 1);
                }
            }
        } catch (Exception e) {
            // 处理异常情况
        }
        return url; // fallback
    }
}
